import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

String inputEyesClose = 'assets/images/input_eyes_close.png';
String inputEyesOpen = 'assets/images/input_eyes_open.png';

///
/// 输入框类型
/// phone: 手机+区号，
/// email、text、number: 键盘区别
///
enum InputType { phone, email, text, number }

///
/// 输入框公共类
///
class LxTextField extends StatefulWidget {
  /// 控制器
  final TextEditingController? controller;

  /// 默认文本
  final String? value;

  /// 内容颜色
  final Color textFieldTextColor;

  /// 内容风格
  final LxFontWeightEnum textFontWeight;

  /// 提示文本
  final String? placeholder;

  /// 输入框类型
  final InputType? textFieldType;

  /// 输入框头部icon
  final Image? prefixIcon;

  /// 默认手机区号
  final String? areaCode;

  /// 背景色
  final Color? backgroundColor;

  /// 背景高度
  final double? bgHeight;

  /// 背景边框
  final BoxBorder? bgBorder;

  /// 背景圆角
  final BorderRadiusGeometry? bgBorderRadius;

  /// 默认边框色
  final Color? enabledBorderColor;

  /// 编辑时边框色
  final Color? focusedBorderColor;

  /// 背景外间距
  final EdgeInsetsGeometry? bgMargin;

  /// 内边距
  final EdgeInsetsGeometry? bgPadding;

  // /// 内容间隔
  // final double? contentPaddignAll;

  final TextAlign? textAlign;

  /// 高度
  final int? maxLines;

  /// 最大长度
  final int? maxLength;

  /// 是否显示删除按钮
  final bool? showClear;

  /// 是否自动获取焦点
  final bool? autofocus;

  final bool? enabled;

  /// 输入框内容改变回调
  final void Function(String)? onChangedValue;

  /// 手机区号选择回调
  final void Function(String)? onChangedAreaCode;

  // 输入完成
  final void Function(String)? onSubmitted;

  // 是否显示秘文
  final bool? isShowSecret;

  // 是否是秘文
  final bool? isSecret;

  const LxTextField({
    Key? key,
    @required this.placeholder,
    @required this.textFieldType,
    @required this.controller,
    this.areaCode,
    this.value,
    this.textFontWeight = LxFontWeightEnum.bodyLarge,
    this.textFieldTextColor = WhiteColor.white1,
    this.backgroundColor,
    this.bgHeight,
    this.bgBorder,
    this.bgBorderRadius,
    this.enabledBorderColor,
    this.focusedBorderColor,
    this.prefixIcon,
    this.bgMargin,
    this.bgPadding,
    this.textAlign = TextAlign.start,
    this.maxLines,
    this.maxLength,
    this.showClear,
    this.autofocus,
    this.enabled,
    this.onChangedValue,
    this.onChangedAreaCode,
    this.onSubmitted,
    this.isShowSecret = false,
    this.isSecret = false,
  }) : super(key: key);

  @override
  LxTextFieldState createState() => LxTextFieldState();
}

/// 使用WidgetsBindingObserver监听键盘的弹出和隐藏
class LxTextFieldState extends State<LxTextField> with WidgetsBindingObserver {
  /// 监听焦点，显示清空按钮
  final FocusNode _focusNode = FocusNode();

  /// 显示清空按钮
  bool _showClear = false;

  /// 是否显示秘文（密码）
  bool _showSecret = true;

  String? _areaCode;

  // IconData _eyeIcon = Icons.remove_red_eye_rounded;

  String _eyeIcon = inputEyesClose;

  @override
  void initState() {
    super.initState();

    _showSecret = widget.isSecret ?? false;

    // 设置默认值
    widget.controller?.text = widget.value ?? "";

    if (widget.showClear == true) {
      /// 添加监听
      _focusNode.addListener(_focusNodeListener);
    }

    _areaCode = widget.areaCode ?? '86';

    // /// 创建一个界面变化的观察者
    // WidgetsBinding.instance?.addObserver(this);

    if (widget.autofocus == true) {
      Timer(const Duration(milliseconds: 30), () {
        FocusScope.of(context).requestFocus(_focusNode);
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (widget.showClear == true) {
      /// 移除监听
      _focusNode.removeListener(_focusNodeListener);
    }
  }

  Future<void> _focusNodeListener() async {
    reloadClearBtn();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: widget.bgMargin,
      padding: widget.bgPadding ??
          const EdgeInsets.only(left: 0, right: 0, top: 0, bottom: 0),
      height: widget.bgHeight ?? 48.h,
      decoration: BoxDecoration(
          border: widget.bgBorder,
          borderRadius: widget
              .bgBorderRadius, // BorderRadius.circular(widget.bgRadius ?? 0),
          color: widget.backgroundColor),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          widget.textFieldType == InputType.phone
              ? GestureDetector(
                  child: DropdownButton(
                    items: null,
                    //设置菜单组，
                    onChanged: (value) {},
                    // 提示控件，你可以弄成文字或者是图片（如果有value，value的文字会显示在最上面，这就是问题的所在，这个文字的颜色是items控件里面的颜色，这样会导致按钮颜色不能控制，唯一的办法目前就是去掉value）
                    hint: Text(
                      '+${_areaCode ?? ''}',
                      style: TextStyle(
                        color: WhiteColor.white2,
                        fontSize: widget.textFontWeight.size,
                        fontWeight: widget.textFontWeight.fontWeight,
                      ),
                    ),
                    isDense: true,
                    // value: '',
                    underline: const SizedBox.shrink(),
                    style: TextStyle(
                      color: widget.textFieldTextColor,
                      fontSize: widget.textFontWeight.size,
                    ),
                    iconEnabledColor: widget.textFieldTextColor,
                    iconDisabledColor: widget.textFieldTextColor,
                    onTap: () {},
                  ),
                  onTap: () {
                    /// 跳转选择国家码界面
                  })
              : const SizedBox.shrink(),

          /// TextField 不能直接放入Row 中，会报错
          /// 使用Expanded实现Row中所有组件平均分配剩余空间
          Expanded(
            child: TextField(
              controller: widget.controller,
              onEditingComplete: () {
                // 输入完成隐藏键盘
                FocusScope.of(context).requestFocus(FocusNode());
              },
              textAlign: widget.textAlign!,
              enabled: widget.enabled,
              keyboardType: _getKeyboardType(),
              focusNode: _focusNode,
              // autofocus: widget.autofocus ?? false,
              maxLines: widget.maxLines ?? 1,
              maxLength: widget.maxLength ?? 50,
              // 设置最大长度
              // 输入密码，需要用*****显示
              obscureText: _showSecret,
              decoration: InputDecoration(
                  counterText: '',
                  // 控制最大字符是否显示，默认显示当前/最大字符数（0/20）
                  contentPadding: EdgeInsets.only(
                    left: CONTENT_MARGIN,
                  ),
                  hintText: widget.placeholder,
                  hintStyle: TextStyle(
                    color: WhiteColor.white2,
                    fontSize: widget.textFontWeight.size,
                    fontWeight: widget.textFontWeight.fontWeight,
                  ),

                  /// 文本框的头部图标
                  prefixIcon: widget.prefixIcon != null
                      ? Padding(
                          padding: const EdgeInsets.only(left: 10),
                          child: widget.prefixIcon,
                        )
                      : null,

                  /// 文本框的尾部图标
                  suffixIcon: _buildClear(),
                  // border: InputBorder.none
                  /// 设置边框（使用边框能保证内容居中显示，不需要可设置为透明）
                  border: const OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.transparent),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: widget.enabledBorderColor ??
                          Colors.transparent, // 默认展示边框色
                    ),
                  ),
                  disabledBorder: const OutlineInputBorder(
                    borderSide: BorderSide(
                      color: Colors.transparent,
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: widget.focusedBorderColor ??
                          Colors.transparent, // 编辑时边框色
                    ),
                  )),
              // 光标颜色
              cursorColor: LxWidgetsLibraryService.to.colorType.color6,
              style: TextStyle(
                color: widget.textFieldTextColor,
                fontSize: widget.textFontWeight.size,
                fontWeight: widget.textFontWeight.fontWeight,
              ),
              onChanged: (value) {
                reloadClearBtn();
                if (widget.onChangedValue != null) {
                  widget.onChangedValue!(value);
                }
              },
              onSubmitted: (value) {
                // 输入完成隐藏键盘
                FocusScope.of(context).requestFocus(FocusNode());
                if (widget.onSubmitted != null) {
                  widget.onSubmitted!(value);
                }
              },
            ),
          ),

          /// 尾部添加按钮方式二
          Offstage(
            offstage: widget.isShowSecret != true,
            child: GestureDetector(
              onTap: () {
                setState(() {
                  _showSecret = !_showSecret;
                  _eyeIcon = _showSecret ? inputEyesClose : inputEyesOpen;
                });
              },
              child: Padding(
                padding: const EdgeInsets.only(right: 10),
                child: SizedBox(
                  width: 30.w,
                  height: 40.w,
                  // color: Colors.red,
                  child: Image.asset(
                    _eyeIcon,
                    package: PACKAGE_NAME,
                    width: 35,
                    height: 35,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  reloadClearBtn() {
    if (_focusNode.hasFocus &&
        widget.controller != null &&
        widget.controller!.text.isNotEmpty) {
      setState(() {
        _showClear = true;
      });
    } else {
      setState(() {
        _showClear = false;
      });
    }
  }

  /// 删除按钮
  Widget? _buildClear() {
    if (widget.showClear == true && _showClear == true) {
      return IconButton(
          icon: const Icon(Icons.cancel, size: 20, color: Colors.grey),
          onPressed: () {
            widget.controller!.clear();
            if (widget.onChangedValue != null) {
              widget.onChangedValue!('');
            }
            reloadClearBtn();
          });
    }
    return null;
  }

  /// 获取对应的键盘样式
  _getKeyboardType() {
    switch (widget.textFieldType) {
      case InputType.phone:
      case InputType.number:
        return TextInputType.number; // 数字键盘
      case InputType.email:
        return TextInputType.emailAddress; // 邮箱键盘
      default:
        return TextInputType.text; // 文本键盘
    }
  }
}
